package com.example.test.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.test.common.constant.GlobalConstant;
import com.example.test.common.excetion.BusinessException;
import com.example.test.common.utils.AESUtil;
import com.example.test.common.utils.DateUtil;
import com.example.test.common.utils.UserHolder;
import com.example.test.common.utils.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author gyg
 * @version 1.0
 * @date 2020/4/21 11:41
 * @Description: Token拦截器
 */
@Component
public class TokenInterceptor extends UserHolder implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // HandlerMethod handlerMethod = (HandlerMethod) handler;
        // DisableToken disableToken = handlerMethod.getMethodAnnotation(DisableToken.class);
        String token = request.getHeader(GlobalConstant.TOKEN);
        if(StringUtils.isEmpty(token)){
            response.setStatus(401);
            throw new BusinessException("401001","token不能为空");
        } else {
            String str = AESUtil.getInstance().decrypt(token);
            String dateString = str.substring(str.length() - 14);
            String userString = str.substring(0, str.length() - 14);
            Date date = DateUtil.parseDate(dateString);
            Date now = new Date();
            long interval = now.getTime() - date.getTime();
            if(interval / (1000 * 60)>120){
                //有限期两个小时
                response.setStatus(401);
                throw new BusinessException("401002","登录身份失效请重新登陆");
            } else if(interval / (1000 * 60)<120 && interval / (1000 * 60)>115) {
                //自动续期token
                //在剩余5分钟之内继续访问自动续期
                String time = DateUtil.formatDate(new Date(),"yyyyMMddHHmmss");
                String key = userString + time;
                String accessToken = AESUtil.getInstance().encrypt(key);
                response.setHeader(GlobalConstant.TOKEN, accessToken);
            }
            UserInfo userInfo = JSON.parseObject(userString, UserInfo.class);
            USER.set(userInfo);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.clear();
    }
}
